﻿"""Classes which parse input data"""

import re
import errors

class FieldParser(object):
    """Class which provides methods for parsing input form data"""

    @classmethod
    def parse_field_stop(cls, field):
        """Parse form field stop, raises exception if invalid"""
        se_k300 = {'.':'1', ',':'11', '-':'111', '1':'1', 'a':'2', 'b':'22', 'c':'222', '2':'2',
                   'd':'3', 'e':'33', 'f':'333', '3':'3', 'g':'4', 'h':'44', 'i':'444', '4':'4',
                   'j':'5', 'k':'55', 'l':'555', '5':'5', 'm':'6', 'n':'66', 'o':'666', '6':'6',
                   'p':'7', 'q':'77', 'r':'777', '7':'7', 't':'8', 'u':'88', 'v':'888', '8':'8',
                   'w':'9', 'x':'99', 'y':'999', '9':'9', '+':'0', '0':'0', 's':'7777', 'z':'9999'}
        phone_map = lambda s: int(''.join(map(lambda c:se_k300[c], s.lower())))
        if re.match(r'[\s,;]*[a-zA-Z0-9]{1,4}([\s,;]+[a-zA-Z0-9]{1,4})*[\s,;]*$', field) is not None:
            return map(phone_map, re.findall(r'[a-zA-Z0-9]{1,4}', field))
        else:
            raise errors.InvalidFieldStopError(field)
            
    @classmethod
    def parse_field_line(cls, field):
        """Parse form field line, raises exception if invalid"""
        if re.match(r'[\s,;]*(\w+([\s,;]+\w+)*)?[\s,;]*$', field) is not None:
            return map(lambda s:s.lower(), re.findall(r'\w+', field))
        else:
            raise errors.InvalidFieldLineError(field)
            
    @classmethod
    def parse_field_time(cls, field):
        """Parse form field time, raises exception if invalid"""
        if re.match(r' *\d* *$', field) is not None:
            m = re.search(r'\d+', field)
            return (int(m.group(0)) if m else None)
        else:
            raise errors.InvalidFieldTimeError(field)
    
    @classmethod
    def parse_field_pagename(cls, field):
        """Parse form field pagename, raises exception if invalid"""
        if re.match(r' *(\w+( +\w+)*) *$', field) is not None:
            return re.search(r'\w+( +\w+)*', field).group(0)
        else:
            raise errors.InvalidFieldPageNameError(field)
